package com.bosssoft.trainee.nontax.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bosssoft.trainee.nontax.util.CustomRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class SqlInjectFilter implements Filter {
    private static final String SQL_REG_EXP = ".*(\\b(select|insert|into|update|delete|from|where|and|or|trancate" +
            "|drop|execute|like|grant|use|union|order|by)\\b).*";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain){
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        CustomRequestWrapper requestWrapper = null;
        try {
            requestWrapper = new CustomRequestWrapper(request);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Map<String, Object> parameterMap = new HashMap<>();
        parameterMap =getParameterMap(parameterMap, request, requestWrapper);

        // 正则校验是否有SQL关键字
        for (Map.Entry entry : parameterMap.entrySet()) {
            Object value = entry.getValue();
            if (value != null) {
                boolean isValid = false;
                try {
                    isValid = isSqlInject(value.toString(), servletResponse);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (!isValid) {
                    return;
                }
            }
        }
        try {
            filterChain.doFilter(requestWrapper, servletResponse);
        } catch (IOException | ServletException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {

    }

    private Map<String, Object> getParameterMap(Map<String, Object> paramMap, HttpServletRequest request, CustomRequestWrapper requestWrapper) {
        // 1.POST请求获取参数
        if ("POST".equalsIgnoreCase(request.getMethod().toUpperCase())) {
            String body = requestWrapper.getBody();
            if (body == null || body.length() == 0) {
                return paramMap;
            }
            paramMap = JSONObject.parseObject(body, HashMap.class);
        } else {
            Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
            if (parameterMap != null && parameterMap.size() > 0) {
                Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
                for (Map.Entry<String, String[]> next : entries) {
                    paramMap.put(next.getKey(), next.getValue()[0]);
                }
            } else {
                String afterDecodeUrl = null;
                try {
                    afterDecodeUrl = URLDecoder.decode(request.getRequestURI(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                paramMap.put("pathVar", afterDecodeUrl);
            }
        }
        return paramMap;
    }
    private boolean isSqlInject(String value, ServletResponse servletResponse) throws IOException {
        if (null != value && value.toLowerCase().matches(SQL_REG_EXP)) {
            log.info("入参中有非法字符: " + value);
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Map<String, String> responseMap = new HashMap<>();

            responseMap.put("code", "900");
            responseMap.put("message","入参中有非法字符");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write(JSON.toJSONString(responseMap));
            response.getWriter().flush();
            response.getWriter().close();
            return false;
        }
        return true;
    }
}